<template>
  <!-- 房间列表 -->
  <q-page class="row justify-center q-gutter-sm">
    <div class="row justify-center q-gutter-sm">
      <q-intersection
        v-for="room in rooms"
        :key="room.id"
        transition="scale"
        class="item"
      >
        <q-card class="q-ma-sm">
          <q-icon color="secondary" :name="mdiVideoBox" />
          <q-card-section class="bg-secondary text-white">
            <div class="text-h6">{{ room.description }}</div>
            <div class="text-subtitle2">允许人数：{{ room.numbers || 6 }}</div>
          </q-card-section>
          <q-separator />

          <q-card-actions align="right" class="bg-secondary text-white">
            <q-btn flat @click="handleMeeting(room)">申请进入</q-btn>
            <!-- <q-btn flat @click="handleDestroy">退出</q-btn> -->
          </q-card-actions>
        </q-card>
      </q-intersection>
    </div>
    <!-- <q-icon color="primary" :name="mdiVideoBox"  size="4rem" />ffff -->
  </q-page>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from "vue";
import { useRouter } from "vue-router";
import adapter from "webrtc-adapter";
import Janus from "janus-gateway";
import { server, iceServers } from "src/utils/const";
import { useQuasar } from "quasar";
import { getRooms } from "src/api/rooms";
import { mdiVideoBox } from "@quasar/extras/mdi-v7";

const plugin = "janus.plugin.videoroom";
var opaqueId = "videoroom-" + Janus.randomString(12);
var janus = null; // 保存janus实例
var pluginHandler = null; // 保存插件句柄

const $q = useQuasar();

const router = useRouter();

defineOptions({
  name: "IndexPage",
});

const rooms = ref([]);

let room_list = [];
// janus初始化
const initJanus = function () {
  Janus.init({
    debug: "all",
    dependencies: Janus.useDefaultDependencies({
      adapter: adapter,
    }),
    callback: () => {
      if (!Janus.isWebrtcSupported()) {
        console.log("is not Supported Webrtc!");
        $q.notify({
          message: "不支持WebRtc!",
          color: "primary",
        });
        return;
      }
      console.log("初始化完毕");
      createSession();
    },
  });
};

// 创建会话
const createSession = function () {
  janus = new Janus({
    server: server,
    iceServers: iceServers,
    success: function () {
      console.log("success", janus.getServer());
      attachVideoRoomPlugin();
    },
    error: function (error) {
      Janus.error(error);
      // window.location.reload();
      $q.notify({
        message: error,
        icon: "announcement",
        color: "red",
      });
    },
    destroyed: function () {
      console.log("destroyed");
      // window.location.reload();
    },
  });
};

//附件VideoRoom插件
const attachVideoRoomPlugin = function () {
  janus.attach({
    plugin: plugin,
    opaqueId: opaqueId,
    success: function (pluginHandle) {
      pluginHandler = pluginHandle;
      Janus.log(
        "Plugin attached! (" +
          pluginHandler.getPlugin() +
          ", id=" +
          pluginHandler.getId() +
          ")"
      );
      Janus.log("  -- This is a publisher/manager");
      // getVideoRooms();
      const list = { request: "list" };
      pluginHandler.send({
        message: list,
        success: (res) => {
          if (res.videoroom === "success") {
            room_list = res.list;
            Janus.debug(room_list);
          }
          getVideoRooms();
        },
        error: (err) => {
          Janus.error("  -- Error requset list", err);
        },
      });
    },
    error: function (error) {
      Janus.error("  -- Error attaching plugin...", error);
      $q.notify({
        message: "  -- Error attaching plugin... " + error,
        color: "red",
      });
    },
    oncleanup: function () {
      Janus.log(" ::: Got a cleanup notification: we are unpublished now :::");
      Janus.log(" ::: Got a cleanup notification :::");
    },
  });
};

function getVideoRooms() {
  getRooms().then((res) => {
    console.log(res);
    rooms.value = res;
    ///创建房间
    for (let i in rooms.value) {
      let room = rooms.value[i];
      let index = room_list.findIndex((item) => item.room === room.id);
      if (index == -1) {
        handleCreate(room);
      }
    }
  });
}
//创建视频房间
function handleCreate(room) {
  let createRoom = {
    request: "create",
    publishers: room.numbers,
    room: room.id,
    description: room.description,
    secret: room.secret,
    pin: room.pin,
    permanent: false,
  };
  pluginHandler.send({
    message: createRoom,
    success: (res) => {
      console.log(res);
      if (res.videoroom == "created") {
        $q.notify({
          message: "房间:" + res.room + "创建成功",
          color: "green",
        });
      }
    },
  });
}

function handleMeeting(room_data) {
  console.log(room_data.id);
  router.replace({
    name: "Meeting",
    params: { room: room_data.id },
  });
}

function handleDestroy() {
  // janus.destroy();
}

onMounted(() => {
  initJanus();
});

onUnmounted(() => {
  pluginHandler.hangup();
  pluginHandler.detach();
  janus.destroy();
});
</script>
<style lang="scss" scoped>
.item {
  height: 300px;
  width: 300px;
}

.q-card > .q-icon {
  width: 100%;
  height: 150px;
}
</style>
